package com.wangy.sct.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wangy.sct.common.core.SctConstants;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * ClassName: JwtUtil <br/>
 * Description:  <br/>
 *
 * @author wangyue
 * @version V1.0.0
 * @date 2018/11/6 2:32 PM
 */
public class JwtUtil {

	private static final String JWT_SECRET = "alsdjlAKSjd9823847923hn_j2?h";

	/**
	 * @Description: 生成签名, EXPIRE_TIME 后过期
	 * @param: [userId, expireTime]
	 * @return: java.lang.String
	 * @author: wangyue
	 * @Date: 2018/11/6 2:35 PM
	 */
	public static String sign(String userId, long expireTime) throws UnsupportedEncodingException {
		Date date = new Date(System.currentTimeMillis() + expireTime);
		Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
		// 附带user_id信息
		return JWT.create()
				.withIssuer(SctConstants.JWT_ISSUER)
				.withClaim(SctConstants.JWT_CLAIM_USERID, userId)
				.withExpiresAt(date)
				.sign(algorithm);
	}

	/**
	 * @Description: 校验token是否正确
	 * @param: [token]
	 * @return: java.util.Map<java.lang.String, com.auth0.jwt.interfaces.Claim>
	 * @author: wangyue
	 * @Date: 2018/11/8 10:40 AM
	 */
	public static Map<String, Claim> verify(String token) throws UnsupportedEncodingException {
		Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
		JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWT.require(algorithm).withIssuer(SctConstants.JWT_ISSUER);
		// 验证是否超时
		JWTVerifier jwtVerifier = verification.build(() -> new Date());
		DecodedJWT jwt = jwtVerifier.verify(token);
		return jwt.getClaims();
	}

	/**
	 * @Description: 先验证，然后获得token中的信息
	 * @param: [token, claimName]
	 * @return: java.lang.String
	 * @author: wangyue
	 * @Date: 2018/11/6 3:18 PM
	 */
	public static String getClaimValue(String token, String claimName) throws UnsupportedEncodingException {
		Map<String, Claim> claimMap = verify(token);
		return claimMap.get(claimName).asString();
	}

}
